package org.dea.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class GenericCommandLineExecutor {

	private Process process;
	private StreamGobbler streamGobblerErr;
	private String[] commands;
	private StreamGobbler streamGobblerStd;

	public GenericCommandLineExecutor(String[] commands) {
		super();
		this.commands = commands;
	}

	/**
	 * Runs a command.
	 * 
	 * @param commands
	 *            The command.
	 * @throws Exception
	 *             Case there's any problem.
	 */
	public void runCommand()
			throws Exception {
		String command = "";
		for (int k = 0; k < commands.length; k++) {
			command += commands[k] + " ";
		}

		Runtime exec = Runtime.getRuntime();
		process = exec.exec(commands);
		streamGobblerErr = new StreamGobbler(process
				.getErrorStream(), "ERROR");
		streamGobblerErr.start();
		streamGobblerStd = new StreamGobbler(process
				.getInputStream(), "STD");
		streamGobblerStd.start();
	}
	
	public int waitFor() throws InterruptedException {
		if (process == null) {
			throw new RuntimeException("Unstarted process!");
		}
		return process.waitFor();
	}
	
	
	public String getStdOutput() {
		return getOutput(streamGobblerStd);
	}

	public String getErrOutput() {
		return getOutput(streamGobblerErr);
	}

	private String getOutput(StreamGobbler streamGobbler) {
		if (process == null) {
			throw new RuntimeException("Unstarted process!");
		}
		return streamGobbler.getOutput();
		
	}
	
	
}

class StreamGobbler extends Thread {
	private InputStream is;

	private String type;

	private StringBuffer output;
	
	StreamGobbler(InputStream is, String type) {
		this.is = is;
		this.type = type;
		this.output = new StringBuffer();
	}

	public void run() {
		try {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null ) {
				output.append("["+ type + "] " + line + System.getProperty("line.separator"));
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	public String getOutput() {
		return output.toString();
	}
}
 